public int reverseNumber(int number){
int reverse = 0;
while(number != 0){
reverse = (reverse*10)+(number%10);
number = number/10;
}
return reverse;
}
Sunday, June 26, 2016
Maximum repeated words from file
mport java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Map.Entry;
public class MaxDuplicateWordCount {
public Map getWordCount(String fileName){
FileInputStream fis = null;
DataInputStream dis = null;
BufferedReader br = null;
Map wordMap = new HashMap();
try {
fis = new FileInputStream(fileName);
dis = new DataInputStream(fis);
br = new BufferedReader(new InputStreamReader(dis));
String line = null;
while((line = br.readLine()) != null){
StringTokenizer st = new StringTokenizer(line, " ");
while(st.hasMoreTokens()){
String tmp = st.nextToken().toLowerCase();
if(wordMap.containsKey(tmp)){
wordMap.put(tmp, wordMap.get(tmp)+1);
} else {
wordMap.put(tmp, 1);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try{if(br != null) br.close();}catch(Exception ex){}
}
return wordMap;
}
public List> sortByValue(Map wordMap){
Set> set = wordMap.entrySet();
List> list = new ArrayList>(set);
Collections.sort( list, new Comparator
{
public int compare( Map.Entry o1, Map.Entry o2 )
{
return (o2.getValue()).compareTo( o1.getValue() );
}
} );
return list;
}
public static void main(String a[]){
MaxDuplicateWordCount mdc = new MaxDuplicateWordCount();
Map wordMap = mdc.getWordCount("C:/MyTestFile.txt");
List> list = mdc.sortByValue(wordMap);
for(Map.Entry entry:list){
System.out.println(entry.getKey()+" ==== "+entry.getValue());
}
}
}
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Map.Entry;
public class MaxDuplicateWordCount {
public Map
FileInputStream fis = null;
DataInputStream dis = null;
BufferedReader br = null;
Map
try {
fis = new FileInputStream(fileName);
dis = new DataInputStream(fis);
br = new BufferedReader(new InputStreamReader(dis));
String line = null;
while((line = br.readLine()) != null){
StringTokenizer st = new StringTokenizer(line, " ");
while(st.hasMoreTokens()){
String tmp = st.nextToken().toLowerCase();
if(wordMap.containsKey(tmp)){
wordMap.put(tmp, wordMap.get(tmp)+1);
} else {
wordMap.put(tmp, 1);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try{if(br != null) br.close();}catch(Exception ex){}
}
return wordMap;
}
public List
Set
List
Collections.sort( list, new Comparator
{
public int compare( Map.Entry
{
return (o2.getValue()).compareTo( o1.getValue() );
}
} );
return list;
}
public static void main(String a[]){
MaxDuplicateWordCount mdc = new MaxDuplicateWordCount();
Map
List
for(Map.Entry
System.out.println(entry.getKey()+" ==== "+entry.getValue());
}
}
}
Duplicate characters in a String
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class DuplicateCharsInString {
public void findDuplicateChars(String str){
Map dupMap = new HashMap();
char[] chrs = str.toCharArray();
for(Character ch:chrs){
if(dupMap.containsKey(ch)){
dupMap.put(ch, dupMap.get(ch)+1);
} else {
dupMap.put(ch, 1);
}
}
Set keys = dupMap.keySet();
for(Character ch:keys){
if(dupMap.get(ch) > 1){
System.out.println(ch+"--->"+dupMap.get(ch));
}
}
}
public static void main(String a[]){
DuplicateCharsInString dcs = new DuplicateCharsInString();
dcs.findDuplicateChars("Java2Novice");
}
}
import java.util.Map;
import java.util.Set;
public class DuplicateCharsInString {
public void findDuplicateChars(String str){
Map
char[] chrs = str.toCharArray();
for(Character ch:chrs){
if(dupMap.containsKey(ch)){
dupMap.put(ch, dupMap.get(ch)+1);
} else {
dupMap.put(ch, 1);
}
}
Set
for(Character ch:keys){
if(dupMap.get(ch) > 1){
System.out.println(ch+"--->"+dupMap.get(ch));
}
}
}
public static void main(String a[]){
DuplicateCharsInString dcs = new DuplicateCharsInString();
dcs.findDuplicateChars("Java2Novice");
}
}
Swapping two numbers
public static void main(String a[]){
int x = 10;
int y = 20;
System.out.println("Before swap:");
System.out.println("x value: "+x);
System.out.println("y value: "+y);
x = x+y;
y=x-y;
x=x-y;
System.out.println("After swap:");
System.out.println("x value: "+x);
System.out.println("y value: "+y);
}
int x = 10;
int y = 20;
System.out.println("Before swap:");
System.out.println("x value: "+x);
System.out.println("y value: "+y);
x = x+y;
y=x-y;
x=x-y;
System.out.println("After swap:");
System.out.println("x value: "+x);
System.out.println("y value: "+y);
}
Get Distinct word
public List getDistinctWordList(String fileName){
FileInputStream fis = null;
DataInputStream dis = null;
BufferedReader br = null;
List wordList = new ArrayList();
try {
fis = new FileInputStream(fileName);
dis = new DataInputStream(fis);
br = new BufferedReader(new InputStreamReader(dis));
String line = null;
while((line = br.readLine()) != null){
StringTokenizer st = new StringTokenizer(line, " ,.;:\"");
while(st.hasMoreTokens()){
String tmp = st.nextToken().toLowerCase();
if(!wordList.contains(tmp)){
wordList.add(tmp);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try{if(br != null) br.close();}catch(Exception ex){}
}
return wordList;
}
FileInputStream fis = null;
DataInputStream dis = null;
BufferedReader br = null;
List
try {
fis = new FileInputStream(fileName);
dis = new DataInputStream(fis);
br = new BufferedReader(new InputStreamReader(dis));
String line = null;
while((line = br.readLine()) != null){
StringTokenizer st = new StringTokenizer(line, " ,.;:\"");
while(st.hasMoreTokens()){
String tmp = st.nextToken().toLowerCase();
if(!wordList.contains(tmp)){
wordList.add(tmp);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try{if(br != null) br.close();}catch(Exception ex){}
}
return wordList;
}
Delete Particular Element of Array
String[] str_array = {"item1","item2","item3"};
List list = new ArrayList(Arrays.asList(str_array));
list.remove("item2");
str_array = list.toArray(new String[0]);
System.out.println(Arrays.toString(str_array));
public static String[] removeItemFromArray(String[] input, String item) {
if (input == null) {
return null;
} else if (input.length <= 0) {
return input;
} else {
String[] output = new String[input.length - 1];
int count = 0;
for (String i : input) {
if (!i.equals(item)) {
output[count++] = i;
}
}
return output;
}
}
List
list.remove("item2");
str_array = list.toArray(new String[0]);
System.out.println(Arrays.toString(str_array));
public static String[] removeItemFromArray(String[] input, String item) {
if (input == null) {
return null;
} else if (input.length <= 0) {
return input;
} else {
String[] output = new String[input.length - 1];
int count = 0;
for (String i : input) {
if (!i.equals(item)) {
output[count++] = i;
}
}
return output;
}
}
String[] strArr = new String[]{"google","microsoft","apple"};
final List list = new ArrayList();
Collections.addAll(list, strArr);
list.remove("apple");
strArr = list.toArray(new String[list.size()]);
System.out.println(Arrays.toString(strArr));
Remove duplicates sorted array
int all[]=new int[]{1,2,1,2,1,3,4,5,2,7};
Arrays.sort(all);
System.out.println(Arrays.toString(all));
HashSetset=new HashSet();
for(Integer a:all)
{
set.add(a);
}
System.out.println(set);
int[] input = {2,3,6,6,8,9,10,10,10,12,12};
ArrayList list = new ArrayList();
for(int i = 0 ; i < input.length; i++)
{
if(!list.contains(input[i]))
{
System.out.println(input[i]);
list.add(input[i]);
}
}
System.out.println(list);
private void removeTheDuplicates(ListmyList) {
for(ListIteratoriterator = myList.listIterator(); iterator.hasNext();) {
Customer customer = iterator.next();
if(Collections.frequency(myList, customer) > 1) {
iterator.remove();
}
}
System.out.println(myList.toString());
}
Set s = new HashSet(listCustomer);
If you need to preserve elements order then use LinkedHashSet instead of HashSet
Set mySet = new LinkedHashSet(list);
list = new ArrayList(set);
import java.util.ArrayList;
public class Arrays extends ArrayList{
@Override
public boolean add(Object e) {
if(!contains(e)){
return super.add(e);
}else{
return false;
}
}
public static void main(String[] args) {
Arrays element=new Arrays();
element.add(1);
element.add(2);
element.add(2);
element.add(3);
System.out.println(element);
}
}
Arrays.sort(all);
System.out.println(Arrays.toString(all));
HashSet
for(Integer a:all)
{
set.add(a);
}
System.out.println(set);
int[] input = {2,3,6,6,8,9,10,10,10,12,12};
ArrayList
for(int i = 0 ; i < input.length; i++)
{
if(!list.contains(input[i]))
{
System.out.println(input[i]);
list.add(input[i]);
}
}
System.out.println(list);
private void removeTheDuplicates(List
for(ListIterator
Customer customer = iterator.next();
if(Collections.frequency(myList, customer) > 1) {
iterator.remove();
}
}
System.out.println(myList.toString());
}
Set
If you need to preserve elements order then use LinkedHashSet instead of HashSet
Set
list = new ArrayList
import java.util.ArrayList;
public class Arrays extends ArrayList{
@Override
public boolean add(Object e) {
if(!contains(e)){
return super.add(e);
}else{
return false;
}
}
public static void main(String[] args) {
Arrays element=new Arrays();
element.add(1);
element.add(2);
element.add(2);
element.add(3);
System.out.println(element);
}
}
Fibonacci Series
class FibonacciExample1{
public static void main(String args[])
{
int n1=0,n2=1,n3,i,count=10;
System.out.print(n1+" "+n2);//printing 0 and 1
for(i=2;i {
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}}
public static void main(String args[])
{
int n1=0,n2=1,n3,i,count=10;
System.out.print(n1+" "+n2);//printing 0 and 1
for(i=2;i
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}}
Saturday, June 25, 2016
File Read
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
// process the line.
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public static void readText throws FileNotFoundException {
Scanner scan = new Scanner(new File("samplefilename.txt"));
while(scan.hasNextLine()){
String line = scan.nextLine();
//Here you can manipulate the string the way you want
}
}
try( BufferedReader reader = new BufferedReader( ... ) ) {
reader.lines().foreach( line -> processLine( line ) );
}
String pathFile="/path/to/file.txt";
String cmd="type";
if(System.getProperty("os.name")=="Linux"){
cmd="cat";
}
Process p= Runtime.getRuntime().exec(cmd+" "+pathFile);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
System.out.println(p.getOutputStream().toString());
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
String line;
while ((line = br.readLine()) != null) {
// process the line.
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public static void readText throws FileNotFoundException {
Scanner scan = new Scanner(new File("samplefilename.txt"));
while(scan.hasNextLine()){
String line = scan.nextLine();
//Here you can manipulate the string the way you want
}
}
try( BufferedReader reader = new BufferedReader( ... ) ) {
reader.lines().foreach( line -> processLine( line ) );
}
String pathFile="/path/to/file.txt";
String cmd="type";
if(System.getProperty("os.name")=="Linux"){
cmd="cat";
}
Process p= Runtime.getRuntime().exec(cmd+" "+pathFile);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
System.out.println(p.getOutputStream().toString());
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
Treeset Sorting
mport java.util.Comparator;
import java.util.TreeSet;
public class MyCompUserDefine {
public static void main(String a[]){
//By using name comparator (String comparison)
TreeSet nameComp = new TreeSet(new MyNameComp());
nameComp.add(new Empl("Ram",3000));
nameComp.add(new Empl("John",6000));
nameComp.add(new Empl("Crish",2000));
nameComp.add(new Empl("Tom",2400));
for(Empl e:nameComp){
System.out.println(e);
}
System.out.println("===========================");
//By using salary comparator (int comparison)
TreeSet salComp = new TreeSet(new MySalaryComp());
salComp.add(new Empl("Ram",3000));
salComp.add(new Empl("John",6000));
salComp.add(new Empl("Crish",2000));
salComp.add(new Empl("Tom",2400));
for(Empl e:salComp){
System.out.println(e);
}
}
}
class MyNameComp implements Comparator{
@Override
public int compare(Empl e1, Empl e2) {
return e1.getName().compareTo(e2.getName());
}
}
class MySalaryComp implements Comparator{
@Override
public int compare(Empl e1, Empl e2) {
if(e1.getSalary() > e2.getSalary()){
return 1;
} else {
return -1;
}
}
}
class Empl{
private String name;
private int salary;
public Empl(String n, int s){
this.name = n;
this.salary = s;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String toString(){
return "Name: "+this.name+"-- Salary: "+this.salary;
}
}
import java.util.TreeSet;
public class MyCompUserDefine {
public static void main(String a[]){
//By using name comparator (String comparison)
TreeSet
nameComp.add(new Empl("Ram",3000));
nameComp.add(new Empl("John",6000));
nameComp.add(new Empl("Crish",2000));
nameComp.add(new Empl("Tom",2400));
for(Empl e:nameComp){
System.out.println(e);
}
System.out.println("===========================");
//By using salary comparator (int comparison)
TreeSet
salComp.add(new Empl("Ram",3000));
salComp.add(new Empl("John",6000));
salComp.add(new Empl("Crish",2000));
salComp.add(new Empl("Tom",2400));
for(Empl e:salComp){
System.out.println(e);
}
}
}
class MyNameComp implements Comparator
@Override
public int compare(Empl e1, Empl e2) {
return e1.getName().compareTo(e2.getName());
}
}
class MySalaryComp implements Comparator
@Override
public int compare(Empl e1, Empl e2) {
if(e1.getSalary() > e2.getSalary()){
return 1;
} else {
return -1;
}
}
}
class Empl{
private String name;
private int salary;
public Empl(String n, int s){
this.name = n;
this.salary = s;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String toString(){
return "Name: "+this.name+"-- Salary: "+this.salary;
}
}
Comparable and Comparator
import java.util.Comparator;
public class Employee implements Comparable<Employee> {
private int id;
private String name;
private int age;
private long salary;
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public long getSalary() {
return salary;
}
public Employee(int id, String name, int age, int salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
@Override
public int compareTo(Employee emp) {
//let's sort the employee based on id in ascending order
//returns a negative integer, zero, or a positive integer as this employee id
//is less than, equal to, or greater than the specified object.
return (this.id - emp.id);
}
@Override
//this is required to print the user friendly information about the Employee
public String toString() {
return "[id=" + this.id + ", name=" + this.name + ", age=" + this.age + ", salary=" +
this.salary + "]";
}
}
/**
* Comparator to sort employees list or array in order of Salary
*/
public static Comparator<Employee> SalaryComparator = new Comparator<Employee>() {
@Override
public int compare(Employee e1, Employee e2) {
return (int) (e1.getSalary() - e2.getSalary());
}
};
/**
* Comparator to sort employees list or array in order of Age
*/
public static Comparator<Employee> AgeComparator = new Comparator<Employee>() {
@Override
public int compare(Employee e1, Employee e2) {
return e1.getAge() - e2.getAge();
}
};
/**
* Comparator to sort employees list or array in order of Name
*/
public static Comparator<Employee> NameComparator = new Comparator<Employee>() {
@Override
public int compare(Employee e1, Employee e2) {
return e1.getName().compareTo(e2.getName());
}
};
.//sort employees array using Comparator by Salary
Arrays.sort(empArr, Employee.SalaryComparator);
System.out.println("Employees list sorted by Salary:\n"+Arrays.toString(empArr));
//sort employees array using Comparator by Age
Arrays.sort(empArr, Employee.AgeComparator);
System.out.println("Employees list sorted by Age:\n"+Arrays.toString(empArr));
//sort employees array using Comparator by Name
Arrays.sort(empArr, Employee.NameComparator);
System.out.println("Employees list sorted by Name:\n"+Arrays.toString(empArr))
import java.util.Comparator;
public class EmployeeComparatorByIdAndName implements Comparator {
@Override
public int compare(Employee o1, Employee o2) {
int flag = o1.getId() - o2.getId();
if(flag==0) flag = o1.getName().compareTo(o2.getName());
return flag;
}
}
import java.util.Arrays;
public class JavaObjectSorting {
/**
* This class shows how to sort custom objects array/list
* implementing Comparable and Comparator interfaces
* @param args
*/
public static void main(String[] args) {
//sorting custom object array
Employee[] empArr = new Employee[4];
empArr[0] = new Employee(10, "Mikey", 25, 10000);
empArr[1] = new Employee(20, "Arun", 29, 20000);
empArr[2] = new Employee(5, "Lisa", 35, 5000);
empArr[3] = new Employee(1, "Pankaj", 32, 50000);
//sorting employees array using Comparable interface implementation
Arrays.sort(empArr);
System.out.println("Default Sorting of Employees list:\n"+Arrays.toString(empArr));
//sort employees array using Comparator by Salary
Arrays.sort(empArr, Employee.SalaryComparator);
System.out.println("Employees list sorted by Salary:\n"+Arrays.toString(empArr));
//sort employees array using Comparator by Age
Arrays.sort(empArr, Employee.AgeComparator);
System.out.println("Employees list sorted by Age:\n"+Arrays.toString(empArr));
//sort employees array using Comparator by Name
Arrays.sort(empArr, Employee.NameComparator);
System.out.println("Employees list sorted by Name:\n"+Arrays.toString(empArr));
//Employees list sorted by ID and then name using Comparator class
empArr[0] = new Employee(1, "Mikey", 25, 10000);
Arrays.sort(empArr, new EmployeeComparatorByIdAndName());
System.out.println("Employees list sorted by ID and Name:\n"+Arrays.toString(empArr));
}
}
Array Sorting
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class JavaObjectSorting {
/**
* This class shows how to sort primitive arrays,
* Wrapper classes Object Arrays
* @param args
*/
public static void main(String[] args) {
//sort primitives array like int array
int[] intArr = {5,9,1,10};
Arrays.sort(intArr);
System.out.println(Arrays.toString(intArr));
//sorting String array
String[] strArr = {"A", "C", "B", "Z", "E"};
Arrays.sort(strArr);
System.out.println(Arrays.toString(strArr));
//sorting list of objects of Wrapper classes
List<String> strList = new ArrayList<String>();
strList.add("A");
strList.add("C");
strList.add("B");
strList.add("Z");
strList.add("E");
Collections.sort(strList);
for(String str: strList) System.out.print(" "+str);
}
}.
User Defined Object Sorting
public class ExampleComparator {
public static void main(String[] args) {
List<Person> list = new ArrayList<Person>();
list.add(new Person("shyam",24));
list.add(new Person("jk",29));
list.add(new Person("paul",30));
list.add(new Person("ashique",4));
list.add(new Person("sreeraj",14));
for (Person person : list) {
System.out.println(person.getName()+ " "+ person.getAge());
}
Collections.sort(list,new PersonComparator());
System.out.println("After sorting");
for (Person person : list) {
System.out.println(person.getName()+ " "+ person.getAge());
}
}
}
public class Person {
private int age;
private String name;
Person (String name, int age){
setName(name);
setAge(age);
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class PersonComparator implements Comparator<Person> {
@Override
public int compare(Person obj1, Person obj2) {
return obj1.getAge() - obj2.getAge();
}
}
class Test {
public int amount; //field u want to compare
// ...
}
Write your custom comparator for this class:
class TestAmountComparator implements Comparator<Test> {
@Override
public int compare(Test t1, Test t2) {
return Integer.valueOf(t1.amount).compareTo(Integer.valueOf(t2.amount))
}
}
To sort the list of your objects:
List<Test> list = new ArrayList<Test>(myTest); //your Test list
//sorting
Collections.sort(list, new TestAmountComparator()); //sort by amount
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public void someTest() {
LinkedList<Person> persons = new LinkedList<Person>();
persons.add(new Person());
//add as many as you want
Collections.sort(persons, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return o1.getName().compareTo(o2.getName());
}
});
}
Sunday, June 19, 2016
Xml SAX and DOM Parser
import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
public class create {
public static void main(String[] args) throws Exception {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter number to add elements in your XML file: ");
String str = bf.readLine();
int no = Integer.parseInt(str);
System.out.print("Enter root: ");
String root = bf.readLine();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
Element rootElement = document.createElement(root);
document.appendChild(rootElement);
for (int i = 1; i <= no; i++){
System.out.print("Enter the element: ");
String element = bf.readLine();
System.out.print("Enter the data: ");
String data = bf.readLine();
Element em = document.createElement(element);
em.appendChild(document.createTextNode(data));
rootElement.appendChild(em);
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(System.out);
StreamResult result1 = new StreamResult("new.xml");
transformer.transform(source, result);
transformer.transform(source, result1);
}
}import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class elecount {
public static void main(String argv[]) {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse("catalog.xml");
NodeList list = doc.getElementsByTagName("CD");
System.out.println("Total of elements : " + list.getLength());
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
}
}
}import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
public class elements{
public static void main(String[] args) {
try{
SAXParserFactory parserFact = SAXParserFactory.newInstance();
SAXParser parser = parserFact.newSAXParser();
System.out.println("XML Elements: ");
DefaultHandler handler = new DefaultHandler(){
public void startElement(String uri, String lName, String ele, Attributes attributes)throws SAXException{
//print elements of xml
System.out.println(ele);
}
};
parser.parse("catalog.xml", handler);
}
catch (Exception e){
e.printStackTrace();
}
}
}import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;
public class getroot{
public static void main(String[] args) {
try{
File file = new File("catalog.xml");
if (file.exists()){
DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = fact.newDocumentBuilder();
Document doc = builder.parse("catalog.xml");
Node node = doc.getDocumentElement();
String root = node.getNodeName();
System.out.println("Root Node: " + root);
}
else{
System.out.println("File not found!");
}
}
catch(Exception e){}
}
}import java.io.*;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
public class readattr {
public static void main(String[] args) {
try {
File file = new File("catalog.xml");
if (file.exists()){
//SAX-implementation:
SAXParserFactory factory = SAXParserFactory.newInstance();
// Create SAX-parser
SAXParser parser = factory.newSAXParser();
System.out.println("Name:\t" + "Value:");
//Define a handler
SaxHandler handler = new SaxHandler();
// Parse the xml document
parser.parse(xmlFile, handler);
}
else{
System.out.println("File not found!");
}
}
catch (Exception e) {
e.printStackTrace();
}
}
private static class SaxHandler extends DefaultHandler {
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXParseException,SAXException {
int length = attrs.getLength();
//Each attribute
for (int i=0; i // Get names and values to each attribute
String name = attrs.getQName(i);
System.out.print(name);
String value = attrs.getValue(i);
System.out.println("\t"+value);
}
}
}
}import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class readsax {
public static void main(String argv[]) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean title = false;
boolean artist = false;
boolean company = false;
boolean price = false;
boolean year = false;
public void startElement(String uri, String localName,String qName,
Attributes attributes) throws SAXException {
System.out.println("Start Element :" + qName);
if (qName.equalsIgnoreCase("TITLE")) {
title = true;
}
if (qName.equalsIgnoreCase("ARTIST")) {
artist = true;
}
if (qName.equalsIgnoreCase("COMPANY")) {
company = true;
}
if (qName.equalsIgnoreCase("PRICE")) {
price = true;
}
if (qName.equalsIgnoreCase("YEAR")) {
year = true;
}
}
public void endElement(String uri, String localName,
String qName) throws SAXException {
System.out.println("End Element :" + qName);
}
public void characters(char ch[], int start, int length) throws SAXException {
if (title) {
System.out.println("Title : " + new String(ch, start, length));
title = false;
}
if (artist) {
System.out.println("Artist : " + new String(ch, start, length));
artist = false;
}
if (company) {
System.out.println("Company : " + new String(ch, start, length));
company = false;
}
if (price) {
System.out.println("Price : " + new String(ch, start, length));
price = false;
}
if (year) {
System.out.println("Year : " + new String(ch, start, length));
year = false;
}
}
};
saxParser.parse("catalog.xml", handler);
} catch (Exception e) {
e.printStackTrace();
}
}
}import java.io.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
public class readxml{
static public void main(String[] arg) {
try{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter XML file name: ");
String xmlFile = bf.readLine();
File file = new File(xmlFile);
if (file.exists()){
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(xmlFile);
// Create transformer
Transformer tFormer = TransformerFactory.newInstance().newTransformer();
// Output text type
//tFormer.setOutputProperty(OutputKeys.METHOD, "text");
// Write the document to a file
Source source = new DOMSource(doc);
Result result = new StreamResult(System.out);
tFormer.transform(source, result);
}
else{
System.out.println("File not found!");
}
}
catch (Exception e){
System.err.println(e);
System.exit(0);
}
}
}import java.io.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
public class rmelement {
static public void main(String[] arg) {
try{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a XML file name: ");
String xmlFile = bf.readLine();
File file = new File(xmlFile);
System.out.print("Enter an element which have to delete: ");
String remElement = bf.readLine();
if (file.exists()){
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(xmlFile);
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer tFormer = tFactory.newTransformer();
Element element = (Element)doc.getElementsByTagName(remElement).item(0);
// Remove the node
element.getParentNode().removeChild(element);
// Normalize the DOM tree to combine all adjacent nodes
doc.normalize();
Source source = new DOMSource(doc);
Result dest = new StreamResult(System.out);
tFormer.transform(source, dest);
System.out.println();
}
else{
System.out.println("File not found!");
}
}
catch (Exception e){
System.err.println(e);
System.exit(0);
}
}
}import org.w3c.dom.*;
import org.apache.xerces.parsers.DOMParser;
import java.io.*;
public class SearchElement{
public static void main(String[] args) {
try{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter file name: ");
String str = bf.readLine();
File file = new File(str);
if (file.exists()){
DOMParser parser = new DOMParser();
parser.parse(str);
Document doc = parser.getDocument();
System.out.print("Enter element that have to count: ");
String ele = bf.readLine();
NodeList list = doc.getElementsByTagName(ele);
if(list.getLength() == 0){
System.out.println("Element doesn't exist in the " + str + " Document.");
}
else{
System.out.println("Element occurrs " + list.getLength() + " times in the " + str);
}
}
else{
System.out.println("File not found!");
}
}
catch (Exception e){
e.getMessage();
}
}
}
import org.w3c.dom.*;
import org.w3c.dom.Node;
import javax.xml.parsers.*;
public class totaltext{
public static boolean isTextNode(Node n){
return n.getNodeName().equals("#text");
}
public static void main(String[]args)throws Exception{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse("catalog.xml");
Element root = doc.getDocumentElement();
System.out.println(root.getNodeName());
NodeList nl = root.getChildNodes();
for(int i=0; i Node ele = nl.item(i);
if(isTextNode(ele)){
continue;
}
System.out.print("\n\n"+ele.getNodeName()+": ");
System.out.println(ele.getFirstChild().getNodeValue()+"\t ");
NodeList innernl= ele.getChildNodes();
for(int j=0; j Node node = innernl.item(j);
if(isTextNode(node))
continue;
System.out.print("\n\n"+node.getNodeName()+": ");
System.out.print(node.getFirstChild().getNodeValue()+"\t ");
}
System.out.println();
}
}
}
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
public class create {
public static void main(String[] args) throws Exception {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter number to add elements in your XML file: ");
String str = bf.readLine();
int no = Integer.parseInt(str);
System.out.print("Enter root: ");
String root = bf.readLine();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
Element rootElement = document.createElement(root);
document.appendChild(rootElement);
for (int i = 1; i <= no; i++){
System.out.print("Enter the element: ");
String element = bf.readLine();
System.out.print("Enter the data: ");
String data = bf.readLine();
Element em = document.createElement(element);
em.appendChild(document.createTextNode(data));
rootElement.appendChild(em);
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(System.out);
StreamResult result1 = new StreamResult("new.xml");
transformer.transform(source, result);
transformer.transform(source, result1);
}
}import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class elecount {
public static void main(String argv[]) {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse("catalog.xml");
NodeList list = doc.getElementsByTagName("CD");
System.out.println("Total of elements : " + list.getLength());
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
}
}
}import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
public class elements{
public static void main(String[] args) {
try{
SAXParserFactory parserFact = SAXParserFactory.newInstance();
SAXParser parser = parserFact.newSAXParser();
System.out.println("XML Elements: ");
DefaultHandler handler = new DefaultHandler(){
public void startElement(String uri, String lName, String ele, Attributes attributes)throws SAXException{
//print elements of xml
System.out.println(ele);
}
};
parser.parse("catalog.xml", handler);
}
catch (Exception e){
e.printStackTrace();
}
}
}import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;
public class getroot{
public static void main(String[] args) {
try{
File file = new File("catalog.xml");
if (file.exists()){
DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = fact.newDocumentBuilder();
Document doc = builder.parse("catalog.xml");
Node node = doc.getDocumentElement();
String root = node.getNodeName();
System.out.println("Root Node: " + root);
}
else{
System.out.println("File not found!");
}
}
catch(Exception e){}
}
}import java.io.*;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
public class readattr {
public static void main(String[] args) {
try {
File file = new File("catalog.xml");
if (file.exists()){
//SAX-implementation:
SAXParserFactory factory = SAXParserFactory.newInstance();
// Create SAX-parser
SAXParser parser = factory.newSAXParser();
System.out.println("Name:\t" + "Value:");
//Define a handler
SaxHandler handler = new SaxHandler();
// Parse the xml document
parser.parse(xmlFile, handler);
}
else{
System.out.println("File not found!");
}
}
catch (Exception e) {
e.printStackTrace();
}
}
private static class SaxHandler extends DefaultHandler {
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXParseException,SAXException {
int length = attrs.getLength();
//Each attribute
for (int i=0; i
String name = attrs.getQName(i);
System.out.print(name);
String value = attrs.getValue(i);
System.out.println("\t"+value);
}
}
}
}import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class readsax {
public static void main(String argv[]) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean title = false;
boolean artist = false;
boolean company = false;
boolean price = false;
boolean year = false;
public void startElement(String uri, String localName,String qName,
Attributes attributes) throws SAXException {
System.out.println("Start Element :" + qName);
if (qName.equalsIgnoreCase("TITLE")) {
title = true;
}
if (qName.equalsIgnoreCase("ARTIST")) {
artist = true;
}
if (qName.equalsIgnoreCase("COMPANY")) {
company = true;
}
if (qName.equalsIgnoreCase("PRICE")) {
price = true;
}
if (qName.equalsIgnoreCase("YEAR")) {
year = true;
}
}
public void endElement(String uri, String localName,
String qName) throws SAXException {
System.out.println("End Element :" + qName);
}
public void characters(char ch[], int start, int length) throws SAXException {
if (title) {
System.out.println("Title : " + new String(ch, start, length));
title = false;
}
if (artist) {
System.out.println("Artist : " + new String(ch, start, length));
artist = false;
}
if (company) {
System.out.println("Company : " + new String(ch, start, length));
company = false;
}
if (price) {
System.out.println("Price : " + new String(ch, start, length));
price = false;
}
if (year) {
System.out.println("Year : " + new String(ch, start, length));
year = false;
}
}
};
saxParser.parse("catalog.xml", handler);
} catch (Exception e) {
e.printStackTrace();
}
}
}import java.io.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
public class readxml{
static public void main(String[] arg) {
try{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter XML file name: ");
String xmlFile = bf.readLine();
File file = new File(xmlFile);
if (file.exists()){
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(xmlFile);
// Create transformer
Transformer tFormer = TransformerFactory.newInstance().newTransformer();
// Output text type
//tFormer.setOutputProperty(OutputKeys.METHOD, "text");
// Write the document to a file
Source source = new DOMSource(doc);
Result result = new StreamResult(System.out);
tFormer.transform(source, result);
}
else{
System.out.println("File not found!");
}
}
catch (Exception e){
System.err.println(e);
System.exit(0);
}
}
}import java.io.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
public class rmelement {
static public void main(String[] arg) {
try{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a XML file name: ");
String xmlFile = bf.readLine();
File file = new File(xmlFile);
System.out.print("Enter an element which have to delete: ");
String remElement = bf.readLine();
if (file.exists()){
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(xmlFile);
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer tFormer = tFactory.newTransformer();
Element element = (Element)doc.getElementsByTagName(remElement).item(0);
// Remove the node
element.getParentNode().removeChild(element);
// Normalize the DOM tree to combine all adjacent nodes
doc.normalize();
Source source = new DOMSource(doc);
Result dest = new StreamResult(System.out);
tFormer.transform(source, dest);
System.out.println();
}
else{
System.out.println("File not found!");
}
}
catch (Exception e){
System.err.println(e);
System.exit(0);
}
}
}import org.w3c.dom.*;
import org.apache.xerces.parsers.DOMParser;
import java.io.*;
public class SearchElement{
public static void main(String[] args) {
try{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter file name: ");
String str = bf.readLine();
File file = new File(str);
if (file.exists()){
DOMParser parser = new DOMParser();
parser.parse(str);
Document doc = parser.getDocument();
System.out.print("Enter element that have to count: ");
String ele = bf.readLine();
NodeList list = doc.getElementsByTagName(ele);
if(list.getLength() == 0){
System.out.println("Element doesn't exist in the " + str + " Document.");
}
else{
System.out.println("Element occurrs " + list.getLength() + " times in the " + str);
}
}
else{
System.out.println("File not found!");
}
}
catch (Exception e){
e.getMessage();
}
}
}
import org.w3c.dom.*;
import org.w3c.dom.Node;
import javax.xml.parsers.*;
public class totaltext{
public static boolean isTextNode(Node n){
return n.getNodeName().equals("#text");
}
public static void main(String[]args)throws Exception{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse("catalog.xml");
Element root = doc.getDocumentElement();
System.out.println(root.getNodeName());
NodeList nl = root.getChildNodes();
for(int i=0; i
if(isTextNode(ele)){
continue;
}
System.out.print("\n\n"+ele.getNodeName()+": ");
System.out.println(ele.getFirstChild().getNodeValue()+"\t ");
NodeList innernl= ele.getChildNodes();
for(int j=0; j
if(isTextNode(node))
continue;
System.out.print("\n\n"+node.getNodeName()+": ");
System.out.print(node.getFirstChild().getNodeValue()+"\t ");
}
System.out.println();
}
}
}
SOAP and Axis WebService Client
import java.net.URL;
import java.util.Vector;
import org.apache.soap.Constants;
import org.apache.soap.rpc.Call;
import org.apache.soap.rpc.Parameter;
import org.apache.soap.rpc.Response;
public class test {
public static void main( String[] args ) throws Exception {
// soap service endpoint
URL url = new URL( "http://localhost:8080/soap/servlet/rpcrouter" );
// create a call
Call call = new Call();
// Service uses standard SOAP encoding
call.setEncodingStyleURI( Constants.NS_URI_SOAP_ENC );
// Set service locator parameters
call.setTargetObjectURI( "urn:ex" );
call.setMethodName( "rstring" );
// Create input parameter vector
Vector params = new Vector();
params.addElement( new Parameter( "s", String.class, "hai da...", null ) );
call.setParams( params );
// Invoke the service, note that an empty SOAPActionURI of
// "" indicates that intent of the SOAP request is taken to
// be the request URI
Response resp = call.invoke( url, "" );
// ... and evaluate the response
if( resp.generatedFault() ) {
throw new Exception();
}
else {
// Call was successful. Extract response parameter and return result
Parameter result = resp.getReturnValue();
System.out.println( "temperature is -> " + result.getValue() );
}
}
}
import java.util.Vector;
import org.apache.soap.Constants;
import org.apache.soap.rpc.Call;
import org.apache.soap.rpc.Parameter;
import org.apache.soap.rpc.Response;
public class test {
public static void main( String[] args ) throws Exception {
// soap service endpoint
URL url = new URL( "http://localhost:8080/soap/servlet/rpcrouter" );
// create a call
Call call = new Call();
// Service uses standard SOAP encoding
call.setEncodingStyleURI( Constants.NS_URI_SOAP_ENC );
// Set service locator parameters
call.setTargetObjectURI( "urn:ex" );
call.setMethodName( "rstring" );
// Create input parameter vector
Vector params = new Vector();
params.addElement( new Parameter( "s", String.class, "hai da...", null ) );
call.setParams( params );
// Invoke the service, note that an empty SOAPActionURI of
// "" indicates that intent of the SOAP request is taken to
// be the request URI
Response resp = call.invoke( url, "" );
// ... and evaluate the response
if( resp.generatedFault() ) {
throw new Exception();
}
else {
// Call was successful. Extract response parameter and return result
Parameter result = resp.getReturnValue();
System.out.println( "temperature is -> " + result.getValue() );
}
}
}
import java.net.URL;
import java.util.Vector;
import org.apache.soap.Constants;
import org.apache.soap.Fault;
import org.apache.soap.rpc.Call;
import org.apache.soap.rpc.Parameter;
import org.apache.soap.rpc.Response;
public class test2{
public static void main(String args[])throws Exception{
System.out.println("hi how are you..");
Call call= new Call();
call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
call.setTargetObjectURI("urn:ex1");
Parameter param1=new Parameter("s",String.class,"99",null);
Vector paramlist=new Vector();
paramlist.addElement(param1);
call.setMethodName("convert");
call.setParams(paramlist);
URL url = new URL("http://localhost:8080/soap/servlet/rpcrouter");
Response result= call.invoke(url,"");
if(result.generatedFault()){
Fault f= result.getFault();
System.out.println(f.getFaultCode());
System.out.println(f.getFaultString());
}
else{
Parameter p=result.getReturnValue();
System.out.println(p.getValue());
}
}
}
/*
* (#) ArithClient.java Mar 19, 2012
*
*/
import org.apache.axiom.om.*;
import org.apache.axis2.client.*;
import org.apache.axis2.addressing.*;
public class ArithClient {
public static void main(String[] args) throws Exception {
String wsdlDocument = "http://localhost:8080/axis2/services/arith?wsdl";
EndpointReference targetEPR = new EndpointReference(wsdlDocument);
OMFactory fac = OMAbstractFactory.getOMFactory();
OMNamespace omNs = fac.createOMNamespace("http://arith", "arith");
OMElement method = fac.createOMElement("add", omNs);
OMElement paramOne = fac.createOMElement("a", omNs);
paramOne.setText("12");
method.addChild(paramOne);
OMElement paramTwo = fac.createOMElement("b", omNs);
paramTwo.setText("10");
method.addChild(paramTwo);
ServiceClient client = new ServiceClient();
Options opts = new Options();
opts.setTo(targetEPR);
client.setOptions(opts);
OMElement res = client.sendReceive(method);
String result = res.getFirstElement().getText();
System.out.println("Result: " + result);
}
}
Java Oracle Database Connectivity
import java.sql.*;
public class JdbcAccessCreate
{
Connection con;
Statement st;
public JdbcAccessCreate()
{
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:abc");
System.out.println("Database Connected");
st=con.createStatement();
String query="create table student(roll number,name text,contactno number)";
st.executeUpdate(query);
System.out.println("Table created successfully");
}catch(Exception e)
{
System.out.println("Error in connection"+e);
}
}
public static void main(String arg[])
{
new JdbcAccessCreate();
}
}
import java.sql.*;
public class JdbcOracleCreate
{
Connection con;
Statement st;
public JdbcOracleCreate()
{
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:abc","scott","tiger");
System.out.println("Database Connected");
st=con.createStatement();
String query="create table student_xx(roll number(4),name varchar2(20),contactno number(10))";
st.executeUpdate(query);
System.out.println("Table created successfully");
}catch(Exception e)
{
System.out.println("Error in connection"+e);
}
}
public static void main(String arg[])
{
new JdbcOracleCreate();
}
}
import java.sql.*;
import java.io.*;
public class JdbcOracleInsert
{
Connection con;
PreparedStatement pst;
public JdbcOracleInsert()
{
try{
char ch='y';
while(ch=='y' || ch=='Y')
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter roll");
int r=Integer.parseInt(br.readLine());
System.out.println("Enter name");
String nm=br.readLine();
System.out.println("Enter Contactno");
int ct=Integer.parseInt(br.readLine());
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:abc","scott","tiger");
System.out.println("Database Connected");
pst=con.prepareStatement("insert into student_xx values(?,?,?)");
pst.setInt(1,r);
pst.setString(2,nm);
pst.setInt(3,ct);
pst.executeUpdate();
System.out.println("Values inserted successfully\nDo u wish to insert more records");
ch=(char)br.read();
}
}catch(Exception e)
{
System.out.println("Error in connection"+e);
}
}
public static void main(String arg[])
{
new JdbcOracleInsert();
}
}
import java.sql.*;
import java.awt.*;
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
public class JdbcOracleInsertJF extends JFrame implements ActionListener
{
Connection con;
int r,ct1;
String nm;
PreparedStatement pst;
JLabel l1,l2,l3;
JTextField t1,t2,t3;
JButton b;
JPanel p,p1,mp;
public JdbcOracleInsertJF()
{
l1=new JLabel("Roll");
l2=new JLabel("Name");
l3=new JLabel("DOB");
t1=new JTextField(20);
t2=new JTextField(20);
t3=new JTextField(20);
b=new JButton("Insert");
b.addActionListener(this);
p=new JPanel(new GridLayout(3,2));
p.add(l1);
p.add(t1);
p.add(l2);
p.add(t2);
p.add(l3);
p.add(t3);
p1=new JPanel();
p1.add(b);
mp=new JPanel(new GridLayout(2,1));
mp.add(p);
mp.add(p1);
Container ct=getContentPane();
ct.setLayout(new FlowLayout());
ct.add(mp);
setTitle("Demo");
setSize(400,400);
setVisible(true);
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:abc","scott","tiger");
JOptionPane.showMessageDialog(this,"Database Connected");
pst=con.prepareStatement("insert into student_xx values(?,?,?)");
}catch(Exception e)
{
System.out.println("Error in connection"+e);
}
}
public void actionPerformed(ActionEvent ae)
{
try{
r=Integer.parseInt(t1.getText());
nm=t2.getText();
ct1=Integer.parseInt(t3.getText());
pst.setInt(1,r);
pst.setString(2,nm);
pst.setInt(3,ct1);
pst.executeUpdate();
JOptionPane.showMessageDialog(this,"Record inserted ");
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error is "+e);
}
}
public static void main(String arg[])
{
new JdbcOracleInsertJF();
}
}
import java.sql.*;
public class JdbcOracleSelect
{
Connection con;
Statement st;
ResultSet rs;
public JdbcOracleSelect()
{
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:abc","scott","tiger");
System.out.println("Database Connected");
st=con.createStatement();
String query="select * from stud_ash";
rs=st.executeQuery(query);
System.out.println("Roll \t Name \t Cont No.");
while(rs.next())
{
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3));
}
}catch(Exception e)
{
System.out.println("Error in connection"+e);
}
}
public static void main(String arg[])
{
new JdbcOracleSelect();
}
}
import java.sql.*;
import java.awt.*;
import java.io.*;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.event.*;
import java.util.*;
public class JdbcOracleSelectAll extends JFrame implements ActionListener
{
Connection con;
ResultSet rs;
Statement st;
ResultSetMetaData rsmd;
JLabel l1,l2;
JTable jtab;
JScrollPane jsp;
JTextField t1;
JButton b_execute;
JPanel p1,p2,mp;
Vector head,row,data;
public JdbcOracleSelectAll()
{
l1=new JLabel("SQL");
l2=new JLabel("Details are");
t1=new JTextField(20);
b_execute=new JButton("Execute");
b_execute.addActionListener(this);
p1=new JPanel();
jtab=new JTable();
int vsp=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
int hsp=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
jsp=new JScrollPane(jtab,vsp,hsp);
p1.add(l1);
p1.add(t1);
p1.add(b_execute);
p2=new JPanel();
p2.add(l2);
p2.add(jsp);
mp=new JPanel();
Container ct=getContentPane();
ct.add(p1,BorderLayout.NORTH);
ct.add(p2,BorderLayout.CENTER);
setTitle("Demo");
setSize(550,400);
setVisible(true);
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:abc","scott","tiger");
JOptionPane.showMessageDialog(this,"Database Connected");
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error in connection"+e);
}
}
public Vector displayData(String query)
{
try{
st=con.createStatement();
rs=st.executeQuery(query);
rsmd=rs.getMetaData();
int cols=rsmd.getColumnCount();
head=new Vector();
for(int i=1;i<=cols;i++)
{
head.add(rsmd.getColumnName(i));
}
data=new Vector();
data.add(head);
while(rs.next())
{
row=new Vector();
for(int i=1;i<=cols;i++)
{
row.add(rs.getString(i));
}
data.add(row);
}
}catch(Exception e)
{
head=new Vector();
head.add("No data found");
data=new Vector();
data.add(head);
}
return data;
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b_execute)
{
try
{
String query=t1.getText();
data=displayData(query);
head=(Vector)data.elementAt(0);
data.removeElementAt(0);
DefaultTableModel dtm=new DefaultTableModel(data,head);
jtab.setModel(dtm);
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error in execute "+e);
}
}
}
public static void main(String arg[])
{
new JdbcOracleSelectAll();
}
}
import java.sql.*;
import java.awt.*;
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
public class JdbcOracleSelectJF extends JFrame implements ActionListener
{
Connection con;
ResultSet rs;
Statement st;
PreparedStatement pst;
JLabel l1,l2,l3;
JTextField t1,t2,t3;
JButton b_insert,b_first,b_next,b_pre,b_last,b_clear;
JPanel p,p1,p2,mp;
public JdbcOracleSelectJF()
{
l1=new JLabel("Roll");
l2=new JLabel("Name");
l3=new JLabel("Contactno");
t1=new JTextField(20);
t2=new JTextField(20);
t3=new JTextField(20);
b_insert=new JButton("Insert");
b_insert.addActionListener(this);
b_first=new JButton(" << ");
b_first.addActionListener(this);
b_pre=new JButton(" < ");
b_pre.addActionListener(this);
b_next=new JButton(" > ");
b_next.addActionListener(this);
b_last=new JButton(" >> ");
b_last.addActionListener(this);
b_clear=new JButton(" Clear");
b_clear.addActionListener(this);
p=new JPanel(new GridLayout(3,2));
p.add(l1);
p.add(t1);
p.add(l2);
p.add(t2);
p.add(l3);
p.add(t3);
p1=new JPanel();
p1.add(b_insert);
p1.add(b_clear);
p2=new JPanel();
p2.add(b_first);
p2.add(b_pre);
p2.add(b_next);
p2.add(b_last);
mp=new JPanel(new GridLayout(3,1));
mp.add(p);
mp.add(p1);
mp.add(p2);
Container ct=getContentPane();
ct.setLayout(new FlowLayout());
ct.add(mp);
setTitle("Demo");
setSize(550,400);
setVisible(true);
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:abc","scott","tiger");
JOptionPane.showMessageDialog(this,"Database Connected");
st=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs=st.executeQuery("select * from student_xx");
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error in connection"+e);
}
}
public void display()
{
try{
t1.setText(""+rs.getInt(1));
t2.setText(""+rs.getString(2));
t3.setText(""+rs.getInt(3));
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error in display "+e);
}
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b_clear)
{
t1.setText("");
t2.setText("");
t3.setText("");
t1.requestFocus();
}
if(ae.getSource()==b_insert)
{
try
{
int r=Integer.parseInt(t1.getText());
String nm=t2.getText();
int ct=Integer.parseInt(t3.getText());
pst=con.prepareStatement("insert into student_xx values(?,?,?)");
pst.setInt(1,r);
pst.setString(2,nm);
pst.setInt(3,ct);
pst.executeUpdate();
JOptionPane.showMessageDialog(this,"Record inserted successfully");
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error in insert "+e);
}
}
if(ae.getSource()==b_first)
{
try{
rs.first();
display();
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error in first "+e);
}
}
if(ae.getSource()==b_pre)
{
try{
if(rs.previous()==false)
{
JOptionPane.showMessageDialog(this,"This is the 1st Record of File ");
}else
display();
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error in pre "+e);
}
}
if(ae.getSource()==b_next)
{
try{
if(rs.next()==false)
{
JOptionPane.showMessageDialog(this,"This is the Last Record ");
}else
display();
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error in next "+e);
}
}
if(ae.getSource()==b_last)
{
try{
rs.last();
display();
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error in last "+e);
}
}
}
public static void main(String arg[])
{
new JdbcOracleSelectJF();
}
}
public class JdbcAccessCreate
{
Connection con;
Statement st;
public JdbcAccessCreate()
{
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:abc");
System.out.println("Database Connected");
st=con.createStatement();
String query="create table student(roll number,name text,contactno number)";
st.executeUpdate(query);
System.out.println("Table created successfully");
}catch(Exception e)
{
System.out.println("Error in connection"+e);
}
}
public static void main(String arg[])
{
new JdbcAccessCreate();
}
}
import java.sql.*;
public class JdbcOracleCreate
{
Connection con;
Statement st;
public JdbcOracleCreate()
{
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:abc","scott","tiger");
System.out.println("Database Connected");
st=con.createStatement();
String query="create table student_xx(roll number(4),name varchar2(20),contactno number(10))";
st.executeUpdate(query);
System.out.println("Table created successfully");
}catch(Exception e)
{
System.out.println("Error in connection"+e);
}
}
public static void main(String arg[])
{
new JdbcOracleCreate();
}
}
import java.sql.*;
import java.io.*;
public class JdbcOracleInsert
{
Connection con;
PreparedStatement pst;
public JdbcOracleInsert()
{
try{
char ch='y';
while(ch=='y' || ch=='Y')
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter roll");
int r=Integer.parseInt(br.readLine());
System.out.println("Enter name");
String nm=br.readLine();
System.out.println("Enter Contactno");
int ct=Integer.parseInt(br.readLine());
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:abc","scott","tiger");
System.out.println("Database Connected");
pst=con.prepareStatement("insert into student_xx values(?,?,?)");
pst.setInt(1,r);
pst.setString(2,nm);
pst.setInt(3,ct);
pst.executeUpdate();
System.out.println("Values inserted successfully\nDo u wish to insert more records");
ch=(char)br.read();
}
}catch(Exception e)
{
System.out.println("Error in connection"+e);
}
}
public static void main(String arg[])
{
new JdbcOracleInsert();
}
}
import java.sql.*;
import java.awt.*;
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
public class JdbcOracleInsertJF extends JFrame implements ActionListener
{
Connection con;
int r,ct1;
String nm;
PreparedStatement pst;
JLabel l1,l2,l3;
JTextField t1,t2,t3;
JButton b;
JPanel p,p1,mp;
public JdbcOracleInsertJF()
{
l1=new JLabel("Roll");
l2=new JLabel("Name");
l3=new JLabel("DOB");
t1=new JTextField(20);
t2=new JTextField(20);
t3=new JTextField(20);
b=new JButton("Insert");
b.addActionListener(this);
p=new JPanel(new GridLayout(3,2));
p.add(l1);
p.add(t1);
p.add(l2);
p.add(t2);
p.add(l3);
p.add(t3);
p1=new JPanel();
p1.add(b);
mp=new JPanel(new GridLayout(2,1));
mp.add(p);
mp.add(p1);
Container ct=getContentPane();
ct.setLayout(new FlowLayout());
ct.add(mp);
setTitle("Demo");
setSize(400,400);
setVisible(true);
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:abc","scott","tiger");
JOptionPane.showMessageDialog(this,"Database Connected");
pst=con.prepareStatement("insert into student_xx values(?,?,?)");
}catch(Exception e)
{
System.out.println("Error in connection"+e);
}
}
public void actionPerformed(ActionEvent ae)
{
try{
r=Integer.parseInt(t1.getText());
nm=t2.getText();
ct1=Integer.parseInt(t3.getText());
pst.setInt(1,r);
pst.setString(2,nm);
pst.setInt(3,ct1);
pst.executeUpdate();
JOptionPane.showMessageDialog(this,"Record inserted ");
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error is "+e);
}
}
public static void main(String arg[])
{
new JdbcOracleInsertJF();
}
}
import java.sql.*;
public class JdbcOracleSelect
{
Connection con;
Statement st;
ResultSet rs;
public JdbcOracleSelect()
{
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:abc","scott","tiger");
System.out.println("Database Connected");
st=con.createStatement();
String query="select * from stud_ash";
rs=st.executeQuery(query);
System.out.println("Roll \t Name \t Cont No.");
while(rs.next())
{
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3));
}
}catch(Exception e)
{
System.out.println("Error in connection"+e);
}
}
public static void main(String arg[])
{
new JdbcOracleSelect();
}
}
import java.sql.*;
import java.awt.*;
import java.io.*;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.event.*;
import java.util.*;
public class JdbcOracleSelectAll extends JFrame implements ActionListener
{
Connection con;
ResultSet rs;
Statement st;
ResultSetMetaData rsmd;
JLabel l1,l2;
JTable jtab;
JScrollPane jsp;
JTextField t1;
JButton b_execute;
JPanel p1,p2,mp;
Vector head,row,data;
public JdbcOracleSelectAll()
{
l1=new JLabel("SQL");
l2=new JLabel("Details are");
t1=new JTextField(20);
b_execute=new JButton("Execute");
b_execute.addActionListener(this);
p1=new JPanel();
jtab=new JTable();
int vsp=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
int hsp=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
jsp=new JScrollPane(jtab,vsp,hsp);
p1.add(l1);
p1.add(t1);
p1.add(b_execute);
p2=new JPanel();
p2.add(l2);
p2.add(jsp);
mp=new JPanel();
Container ct=getContentPane();
ct.add(p1,BorderLayout.NORTH);
ct.add(p2,BorderLayout.CENTER);
setTitle("Demo");
setSize(550,400);
setVisible(true);
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:abc","scott","tiger");
JOptionPane.showMessageDialog(this,"Database Connected");
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error in connection"+e);
}
}
public Vector displayData(String query)
{
try{
st=con.createStatement();
rs=st.executeQuery(query);
rsmd=rs.getMetaData();
int cols=rsmd.getColumnCount();
head=new Vector();
for(int i=1;i<=cols;i++)
{
head.add(rsmd.getColumnName(i));
}
data=new Vector();
data.add(head);
while(rs.next())
{
row=new Vector();
for(int i=1;i<=cols;i++)
{
row.add(rs.getString(i));
}
data.add(row);
}
}catch(Exception e)
{
head=new Vector();
head.add("No data found");
data=new Vector();
data.add(head);
}
return data;
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b_execute)
{
try
{
String query=t1.getText();
data=displayData(query);
head=(Vector)data.elementAt(0);
data.removeElementAt(0);
DefaultTableModel dtm=new DefaultTableModel(data,head);
jtab.setModel(dtm);
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error in execute "+e);
}
}
}
public static void main(String arg[])
{
new JdbcOracleSelectAll();
}
}
import java.sql.*;
import java.awt.*;
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
public class JdbcOracleSelectJF extends JFrame implements ActionListener
{
Connection con;
ResultSet rs;
Statement st;
PreparedStatement pst;
JLabel l1,l2,l3;
JTextField t1,t2,t3;
JButton b_insert,b_first,b_next,b_pre,b_last,b_clear;
JPanel p,p1,p2,mp;
public JdbcOracleSelectJF()
{
l1=new JLabel("Roll");
l2=new JLabel("Name");
l3=new JLabel("Contactno");
t1=new JTextField(20);
t2=new JTextField(20);
t3=new JTextField(20);
b_insert=new JButton("Insert");
b_insert.addActionListener(this);
b_first=new JButton(" << ");
b_first.addActionListener(this);
b_pre=new JButton(" < ");
b_pre.addActionListener(this);
b_next=new JButton(" > ");
b_next.addActionListener(this);
b_last=new JButton(" >> ");
b_last.addActionListener(this);
b_clear=new JButton(" Clear");
b_clear.addActionListener(this);
p=new JPanel(new GridLayout(3,2));
p.add(l1);
p.add(t1);
p.add(l2);
p.add(t2);
p.add(l3);
p.add(t3);
p1=new JPanel();
p1.add(b_insert);
p1.add(b_clear);
p2=new JPanel();
p2.add(b_first);
p2.add(b_pre);
p2.add(b_next);
p2.add(b_last);
mp=new JPanel(new GridLayout(3,1));
mp.add(p);
mp.add(p1);
mp.add(p2);
Container ct=getContentPane();
ct.setLayout(new FlowLayout());
ct.add(mp);
setTitle("Demo");
setSize(550,400);
setVisible(true);
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:abc","scott","tiger");
JOptionPane.showMessageDialog(this,"Database Connected");
st=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs=st.executeQuery("select * from student_xx");
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error in connection"+e);
}
}
public void display()
{
try{
t1.setText(""+rs.getInt(1));
t2.setText(""+rs.getString(2));
t3.setText(""+rs.getInt(3));
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error in display "+e);
}
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b_clear)
{
t1.setText("");
t2.setText("");
t3.setText("");
t1.requestFocus();
}
if(ae.getSource()==b_insert)
{
try
{
int r=Integer.parseInt(t1.getText());
String nm=t2.getText();
int ct=Integer.parseInt(t3.getText());
pst=con.prepareStatement("insert into student_xx values(?,?,?)");
pst.setInt(1,r);
pst.setString(2,nm);
pst.setInt(3,ct);
pst.executeUpdate();
JOptionPane.showMessageDialog(this,"Record inserted successfully");
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error in insert "+e);
}
}
if(ae.getSource()==b_first)
{
try{
rs.first();
display();
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error in first "+e);
}
}
if(ae.getSource()==b_pre)
{
try{
if(rs.previous()==false)
{
JOptionPane.showMessageDialog(this,"This is the 1st Record of File ");
}else
display();
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error in pre "+e);
}
}
if(ae.getSource()==b_next)
{
try{
if(rs.next()==false)
{
JOptionPane.showMessageDialog(this,"This is the Last Record ");
}else
display();
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error in next "+e);
}
}
if(ae.getSource()==b_last)
{
try{
rs.last();
display();
}catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Error in last "+e);
}
}
}
public static void main(String arg[])
{
new JdbcOracleSelectJF();
}
}
Subscribe to:
Posts (Atom)
உப்பு மாங்காய்
சுருக்குப்பை கிழவி. சுருக்கங்கள் சூழ் கிழவி. பார்க்கும் போதெல்லாம் கூடையுடனே குடியிருப்பாள். கூடை நிறைய குட்டி குட்டி மாங்காய்கள். வெட்டிக்க...
-
கந்தன் வேலைக்குச் சென்று கிட்டத்தட்ட பத்து ஆண்டுகளுக்கு பிறகு சொந்த ஊர் திரும்பி இருந்தான். காளிக் கோயிலைத் தாண்டி தான் அவன் வீட்ட...
-
பிரேமாவின் மூத்த ஆண் குழந்தைக்கு முன் பிறந்த இளைய பெண் குழந்தை அவள். வயலும் சேறும் இரண்டற கலந்த ஊர். முழுதாய் மூன்றாம் வகுப்பைத் ...